//
//  HJUserHomePageController.m
//  KaiChat
//
//  Created by lx on 2024/3/26.
//

#import "HJUserHomePageController.h"
#import "HJIM.h"
#import "HJChatController.h"
#import "HJSingleChatSettingController.h"
#import "HJInformationPresent.h"
#import "HJButton.h"
#import "HJTitleSubTitleView.h"
#import "HJFlutterController.h"
#import "HJFirendVerifyController.h"
#import "HJPostHomePageController.h"

@interface HJUserHomePageController ()

@property (nonatomic, weak) UILabel *nicknameLabel;
@property (nonatomic, weak) UILabel *signatureLabel;
@property (nonatomic, weak) UIImageView *avatarImageView;
@property (nonatomic, strong) HJChatUserModel *userModel;
@property (nonatomic, weak) UIImageView *genderImageView;
@property (nonatomic, strong) NSMutableDictionary *titleSubTitleViewPool;
@property (nonatomic, weak) UIView *walletAddressView;
@property (nonatomic, weak) UIView *lineView;
@property (nonatomic, weak) UILabel *addressLabel;
@property (nonatomic, strong) HJButton *followButton;
@property (nonatomic, strong) NSMutableArray *buttonDatas;
@property (nonatomic, weak) UIImageView *topBackgroundImageView;

@end

@implementation HJUserHomePageController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.alpha = 0;
    self.navigationBar.lineView.hidden = YES;
    [self.navigationBar.backBarButton whiteColor];
    
    UIImageView *topBackgroundImageView = [UIImageView addToView:self.view];
    topBackgroundImageView.contentMode = UIViewContentModeScaleAspectFill;
    topBackgroundImageView.image = [UIImage imageWithContentsOfName:@"userHomePage_top_bg" type:@"png"];
    CGFloat imageH = topBackgroundImageView.image.size.height * KScreenWidth / topBackgroundImageView.image.size.width;
    [topBackgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.offset(0);
        make.height.offset(imageH);
    }];
    
    _topBackgroundImageView = topBackgroundImageView;
    [self loadData];
}

- (UIView *)addNewsInfoView {
    UIView *contentView = [[UIView alloc] init];
    for (int i = 0; i < 3; i++) {
        CGFloat W = (KScreenWidth - leftRightMargin * 2) / 3;
        HJTitleSubTitleView *titleSubTitleView = [[HJTitleSubTitleView alloc] init];
        titleSubTitleView.anyObject = @(i);
        [contentView addSubview:titleSubTitleView];
        [self.titleSubTitleViewPool setObject:titleSubTitleView forKey:@(i)];
        [titleSubTitleView addTapGesturesWithTarget:self action:@selector(tapTitleSubTitleView:)];
        [titleSubTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(i * W);
            make.height.offset(40);
            make.width.offset(W);
            make.centerY.offset(0);
        }];
    }
    
    HJTitleSubTitleView *followView = self.titleSubTitleViewPool[@0];
    followView.subTitleLabel.text = @"Follow";
    
    HJTitleSubTitleView *fansView = self.titleSubTitleViewPool[@1];
    fansView.subTitleLabel.text = @"Fans";
    
    HJTitleSubTitleView *postView = self.titleSubTitleViewPool[@2];
    postView.subTitleLabel.text = @"Post";
    
    return contentView;
}

- (void)tapTitleSubTitleView:(UITapGestureRecognizer *)tap {
    
    HJTitleSubTitleView *titleSubTitleView = (HJTitleSubTitleView *)tap.view;
    
    NSInteger index = [titleSubTitleView.anyObject intValue];
    
    if (index == 0) {
        HJFlutterController *flutterController = [[HJFlutterController alloc] initWithName:HJFlutterPageFollow];
        NSMutableDictionary *arguments = [NSMutableDictionary dictionary];
        [arguments setValue:self.nickName forKey:@"username"];
        [arguments setValue:self.userId forKey:@"userId"];
        flutterController.arguments = arguments;
        [self.navigationController pushViewController:flutterController];
        return;
    }
    
    if (index == 1) {
        HJFlutterController *flutterController = [[HJFlutterController alloc] initWithName:HJFlutterPageFans];
        NSMutableDictionary *arguments = [NSMutableDictionary dictionary];
        [arguments setValue:self.nickName forKey:@"username"];
        [arguments setValue:self.userId forKey:@"userId"];
        flutterController.arguments = arguments;
        [self.navigationController pushViewController:flutterController];
        return;
    }
    
    if (index == 2) {
        HJPostHomePageController *postHomePageController = [[HJPostHomePageController alloc] init];
        postHomePageController.userId = self.userModel.userId ?: self.userId;
        [self.navigationController pushViewController:postHomePageController];
        return;
    }
}

- (NSMutableDictionary *)titleSubTitleViewPool {
    if (!_titleSubTitleViewPool) {
        _titleSubTitleViewPool = [NSMutableDictionary dictionary];
    }
    return _titleSubTitleViewPool;
}

- (void)didClickItemButton:(HJButton *)button {
    
    NSString *type = button.anyObject[@"type"];
    //如果不是朋友, 就查询
    if ([type isEqualToString:@"follow"]) {
        [HJHUD showLoadingInView:self.view];
        
        [HJInformationPresent followUser:self.userId complete:^(NSError * _Nullable error) {
            
            if (!error) {
                self.userModel.isFollow = !self.userModel.isFollow;
                if (self.userModel.isFollow) {
                    [HJHUD showSucceedMessage:@"Follow the success"];
                } else {
                    [HJHUD showMessage:@"unfollow"];
                }
                
                if (self.userModel.isFollow) {
                    self.userModel.fans++;
                } else {
                    self.userModel.fans--;
                }
                
                HJTitleSubTitleView *fansView = self.titleSubTitleViewPool[@1];
                fansView.titleLabel.text = toString(@(self.userModel.fans));

                self.followButton.selected = self.userModel.isFollow;
                
                NSLog(@"self.userModel.isFollow = %d", self.userModel.isFollow);
                
                if (self.followStateChanageBlock) {
                    self.followStateChanageBlock(self.userModel.isFollow);
                }
            }
        }];
        return;
    }
    
    if ([type isEqualToString:@"transfer"]) {
        HJFlutterController *flutterController = [[HJFlutterController alloc] initWithName:HJFlutterPageWallet];
        flutterController.arguments = @{
            @"toAddress": self.userModel.walletAddress
        };
        [self.navigationController pushViewController:flutterController];
        return;
    }
    
    if ([type isEqualToString:@"message"] || [type isEqualToString:@"addFriend"]) {
        [HJHUD showLoadingInView:self.view];
        [HJIM.shareIM.userManager loadUserInfoWithUserId:self.userId complete:^(HJChatUserModel * _Nullable model) {
            if (model.isFridend) {
                [self didClickSendMessageButton];
                return;
            }
            
            self.userModel.relationship = model.relationship;
            self.userModel.way = model.way;
            
            HJFirendVerifyController *firendVerifyController = [[HJFirendVerifyController alloc] init];
            firendVerifyController.userId = self.userId;
            firendVerifyController.userModel = self.userModel;
            [firendVerifyController showInController:self];
        }];
        return;
    }
    
}

- (void)didClickSendMessageButton {
    HJChatSessionModel *sessionModel = [HJChatSessionModel sessionModelWithSessionId:toString(self.userModel.sessionId) sessionUserd:toString(self.userModel.userId) chatType:HJChatTypeSingle sessionName:self.userModel.showName];
    [HJChatController showWithSessionModel:sessionModel];
}

- (void)addSubView {
    
    UIImageView *avatarImageView = [UIImageView addToView:self.view];
    avatarImageView.addCornerRadius(34);
    avatarImageView.layer.borderColor = UIColor.whiteColor.CGColor;
    avatarImageView.layer.borderWidth = 1;
    avatarImageView.image = [UIImage imageNamed:defaultAvatarName];
    [avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(leftRightMargin);
        make.width.height.offset(68);
        make.centerY.equalTo(self.topBackgroundImageView.mas_bottom);
    }];
    
    UIView *infoView = [UIView addToView:self.view];
    infoView.backgroundColor = UIColor.whiteColor;
    infoView.addCornerRadius(10);
    infoView.layer.borderColor = UIColor.tj_separatorColor.CGColor;
    infoView.layer.borderWidth = 0.5;
    [infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.equalTo(avatarImageView.mas_bottom).offset(12);
    }];
    
    UILabel *nicknameLabel = [UILabel lableWithSuperView:infoView font:UIFontMediumMake(18) color:UIColor.tj_333333Color title:nil textAlignment:NSTextAlignmentLeft];
    [nicknameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(15);
        make.left.offset(15);
    }];
    
    UILabel *signatureLabel = [UILabel lableWithSuperView:infoView font:UIFontMake(12) color:UIColor.tj_868391Color title:nil textAlignment:NSTextAlignmentLeft];
    signatureLabel.numberOfLines = 0;
    [signatureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nicknameLabel.mas_bottom).offset(4);
        make.left.right.inset(15);
    }];
    
    UIView *walletAddressView = [UIView addToView:infoView];
    walletAddressView.backgroundColor = UIColor.tj_F7F8FAColor;
    walletAddressView.addCornerRadius(5);
    UILabel *addressLabel = [UILabel lableWithSuperView:walletAddressView font:UIFontMake(12) color:UIColor.tj_868391Color title:nil textAlignment:NSTextAlignmentLeft];
    addressLabel.numberOfLines = 0;
    [addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.inset(6);
        make.left.right.inset(15);
    }];
    
    [walletAddressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(signatureLabel);
        make.top.equalTo(signatureLabel.mas_bottom).offset(12);
        make.bottom.equalTo(addressLabel).offset(6);
    }];
    
    if (!TJIM_isSelf(_userId)) {
        
        UIView *lineView = [UIView addToView:infoView];
        lineView.backgroundColor = UIColor.tj_F3F2F7Color;
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(signatureLabel);
            make.height.offset(1);
            make.top.equalTo(walletAddressView.mas_bottom).offset(20);
        }];
        
        UIView *buttonContentView = [UIView addToView:infoView];
        [buttonContentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.inset(15);
            make.height.offset(HZoom(74));
            make.top.equalTo(lineView.mas_bottom).offset(8);
        }];
        
        [infoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(buttonContentView.mas_bottom).offset(15);
        }];
        
        NSMutableArray *buttonDatas = @[
            @{
                @"icon": @"userHomePage_message",
                @"text": @"Message",
                @"type": @"message",
            },
            @{
                @"icon": @"userHomePage_transfer",
                @"text": @"Transfer",
                @"type": @"transfer",
            },
            @{
                @"icon": @"userHomePage_unFollow",
                @"text": @"Follow",
                @"type": @"follow",
            },
        ].mutableCopy;
                
        if (self.userModel.relationship != 1) {
            [buttonDatas insertObject:@{
                @"icon": @"userHomePage_addFriend",
                @"text": @"Add Friend",
                @"type": @"addFriend",
            } atIndex:1];
        }
        
        [buttonDatas enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            CGFloat W = (KScreenWidth - leftRightMargin * 2 - 15 * 2) / buttonDatas.count;
            
            HJButton *itemButton = [HJButton buttonWithSuperView:buttonContentView font:UIFontMake(12) color:UIColor.tj_333333Color title:obj[@"text"]];
            [itemButton setImage:[UIImage imageNamed:obj[@"icon"]] forState:UIControlStateNormal];
            itemButton.anyObject = obj;
            itemButton.imagePosition = QMUIButtonImagePositionTop;
            itemButton.spacingBetweenImageAndTitle = 5;
            [itemButton addTarget:self action:@selector(didClickItemButton:) forControlEvents:UIControlEventTouchUpInside];
            [itemButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.offset(W * idx);
                make.width.offset(W);
                make.top.bottom.offset(0);
            }];
            
            if ([obj[@"type"] isEqualToString:@"follow"]) {
                self.followButton = itemButton;
                [itemButton setImage:[UIImage imageNamed:@"userHomePage_follow"] forState:UIControlStateSelected];
                [itemButton setTitle:@"Followed" forState:UIControlStateSelected];
                [itemButton setTitleColor:UIColor.tj_BEBDCAColor forState:UIControlStateSelected];
                itemButton.selected = self.userModel.isFollow;
            } else if ([obj[@"type"] isEqualToString:@"transfer"]) {
                itemButton.enabled = !isEmptyString(self.userModel.walletAddress);
            }
        }];
        
    } else {
        [infoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(walletAddressView.mas_bottom).offset(20);
        }];
    }
    
    self.signatureLabel = signatureLabel;
    self.nicknameLabel = nicknameLabel;
    self.avatarImageView = avatarImageView;
    self.walletAddressView = walletAddressView;
    self.addressLabel = addressLabel;
    
    
    UIView *newsInfoView = [self addNewsInfoView];
    newsInfoView.backgroundColor = UIColor.whiteColor;
    newsInfoView.addCornerRadius(10);
    newsInfoView.layer.borderColor = UIColor.tj_separatorColor.CGColor;
    newsInfoView.layer.borderWidth = 0.5;
    [self.view addSubview:newsInfoView];
    [newsInfoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(infoView.mas_bottom).offset(15);
        make.left.right.inset(leftRightMargin);
        make.height.offset(60);
    }];
    
}

- (void)handleUserData {
    
    dispatch_async_sql_queue(^{
        HJChatSessionModel *sessionModel = [HJIM.shareIM.conversationManager getConversationBySessionId:self.userModel.sessionId];
        if (sessionModel) {
            sessionModel.sessionUid = sessionModel.uid;
            sessionModel.sessionUserd = self.userModel.userId;
            sessionModel.sessionName = self.userModel.showName;
            [sessionModel bg_saveOrUpdate];
        }
    });
    
    self.lineView.hidden = NO;
    
    HJTitleSubTitleView *followView = self.titleSubTitleViewPool[@0];
    HJTitleSubTitleView *fansView = self.titleSubTitleViewPool[@1];
    HJTitleSubTitleView *postView = self.titleSubTitleViewPool[@2];
    
    followView.titleLabel.text = toString(@(self.userModel.follows));
    fansView.titleLabel.text = toString(@(self.userModel.fans));
    postView.titleLabel.text = toString(@(self.userModel.posts));
    
    [[SDWebImageManager sharedManager] loadImageWithURL:self.userModel.avatar.URL options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        if (image) {
            self.avatarImageView.image = image;
        }
    }];
    
    if (isEmptyString(self.userModel.brief)) {
        self.signatureLabel.text = @"what's up:";
    } else {
        self.signatureLabel.attributedText = [self.userModel.brief titleMargin:3 alignment:NSTextAlignmentLeft];
    }
    
    self.nicknameLabel.text = self.userModel.nickname;
    
    if (isEmptyString(self.userModel.walletAddress)) {
        self.walletAddressView.hidden = YES;
        [self.lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.signatureLabel);
            make.height.offset(1);
            make.top.equalTo(self.signatureLabel.mas_bottom).offset(20);
        }];
    } else {
        self.walletAddressView.hidden = NO;
        self.addressLabel.text = self.userModel.walletAddress;
        [self.lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.signatureLabel);
            make.height.offset(1);
            make.top.equalTo(self.walletAddressView.mas_bottom).offset(20);
        }];
    }
}

- (void)loadData {
    [HJInformationPresent loadUserHomePageDataWithUserId:_userId complete:^(HJChatUserModel * _Nullable userModel) {
        self.userModel = userModel;
        [self addSubView];
        [self handleUserData];
    }];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
- (void)dealloc {
    NSLog(@"%s", __func__);
}

@end
